#include "./varArray.h"

VarArrayStruct* varArray_new() {
  VarArrayStruct* self = (VarArrayStruct*)mem_alloc(sizeof(VarArrayStruct));
  self->length = 0;
  self->maxLength = 32;
  self->data = (void**)mem_alloc(self->maxLength * sizeof(void*));
  return self;
}
void varArray_del(VarArrayStruct* self) {
  mem_free(self);
}

unsigned int varArray_addData(VarArrayStruct* self, void* data) {
  if (self->length >= self->maxLength) {
    self->maxLength <<= 1;
    self->data = (void**)realloc(self->data, self->maxLength);
    if (self->data == NULL) {
      ERROR("varArray can not realloc.");
      // exit(error_memAlloc);
    }
  }
  self->data[self->length++] = data;
  return self->length - 1;
}
void* varArray_delIndex(VarArrayStruct* self, unsigned int i) {
  void* delvar = self->data[i];
  self->data[i] = self->data[--self->length];
  self->data[self->length] = NULL;
  return delvar;
}
unsigned int varArray_findData(VarArrayStruct* self, void* data) {
  unsigned int i;
  for (i = 0; i < self->length; i++) {
    if (self->data[i] == data) {
      break;
    }
  }
  return i;
}
